import  os,time,csv,traceback

class Op_csv:
    def __init__(self):
        currentTime = time.strftime("%Y%m%d%H%M%S", time.localtime())
        projectRootPath = str(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)))
        resultCsv = projectRootPath + '/reports/csv/debug' + currentTime + '.csv'
        csvHeaders = ['用例ID', '测试意图', '请求方式', '请求头', '请求url', '请求data', '响应码', '响应体', '执行结果', '执行时间', '响应时长(ms)', '错误信息',
                      '错误详情']
        initValue = {'用例ID': '', '测试意图': '', '请求方式': '', '请求头': '', '请求url': '', '请求data': '', '响应码': '', '响应体': '',
                     '执行结果': '', '执行时间': '', '响应时长(ms)': '', '错误信息': '', '错误详情': ''}
        if not os.path.isdir(projectRootPath + '/reports/csv'):
            os.makedirs(projectRootPath + '/reports/csv')
        tempA = open(resultCsv, 'w', newline='', encoding='utf-8-sig')
        f_csv = csv.DictWriter(tempA, csvHeaders)
        f_csv.writeheader()
        self.f_csv =f_csv
        self.initValue=initValue

    def writerow_csv(self,row_dict):
        try:
            self.f_csv.writerow(row_dict)
        except Exception as e:
            row_dict['执行结果'] = 'fail'
            initValue['错误信息'] = e.args
            initValue['错误详情'] = traceback.format_exc()
            # raise Exception("写入测试结果文件csv异常，请检查！！！")





if __name__ == '__main__':
    abobo=Op_csv()
    initValue=abobo.initValue
    initValue['执行结果'] = 'pass'
    abobo.writerow_csv(initValue)
    for tempKey in initValue.keys():
        initValue[tempKey] = ''
    initValue['执行结果'] = 'fail'
    abobo.writerow_csv(initValue)


# currentTime = time.strftime("%Y%m%d%H%M%S", time.localtime())
# projectRootPath = str(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)))
#
# resultCsv = projectRootPath + '/reports/csv/debug'+currentTime+'.csv'
# csvHeaders = ['用例ID', '测试意图', '请求方式', '请求头', '请求url', '请求data', '响应码', '响应体', '执行结果', '执行时间', '响应时长','错误信息', '错误详情']
# initValue = {'用例ID': '', '测试意图': '', '请求方式': '', '请求头': '', '请求url': '', '请求data': '', '响应码': '', '响应体': '', '执行结果': '', '执行时间': '','响应时长': '', '错误信息': '', '错误详情': ''}
# # tempInitValue = initValue
#
# if not os.path.isdir(projectRootPath+'/reports/csv'):
#     os.makedirs(projectRootPath+'/reports/csv')
# tempA = open(resultCsv,'w',newline='',encoding='utf-8-sig')
#
# # csvfile.write(codecs.BOM_UTF8)
# f_csv = csv.DictWriter(tempA, csvHeaders)
# f_csv.writeheader()
#
# initValue['执行结果'] = 'pass'
# f_csv.writerow(initValue)
# for tempKey in initValue.keys():
#     initValue[tempKey] = ''
#
# initValue['执行结果'] = 'fail'
# f_csv.writerow(initValue)


# try:
#     f_csv.writerow(initValue)
# except UnicodeEncodeError as exc:
#     initValue['响应体'] = "写入csv时有异常：【" + traceback.format_exc() + "】，请移步测试报告查看详细响应体内容，谢谢~"
#     #     initValue['响应体'] = "写入csv时有疑似中文编码的异常，请移步测试报告查看详细响应体内容，谢谢~"
#     f_csv.writerow(initValue)
# for tempKey in initValue.keys():
#     initValue[tempKey] = ''
